package com.yuanchu.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.common.utils.DateFormatUtils;
import com.yuanchu.store.client.FeignGoodsClient;
import com.yuanchu.store.client.FeignMediaClient;
import com.yuanchu.store.client.FeignOrderClient;
import com.yuanchu.store.dao.*;
import com.yuanchu.store.dto.EditStoreParamsDto;
import com.yuanchu.store.dto.StoreDataDto;
import com.yuanchu.store.dto.StoreSalesDto;
import com.yuanchu.store.dto.TradeTrendVO;
import com.yuanchu.store.entity.*;
import com.yuanchu.store.service.YoshopStoreService;
import com.yuanchu.store.service.YoshopUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("yoshopStoreService")
public class YoshopStoreServiceImpl extends ServiceImpl<YoshopStoreDao, YoshopStoreEntity> implements YoshopStoreService {

    @Resource
    private YoshopStoreUserRoleDao storeUserRoleDao;

    @Resource
    private YoshopStoreRoleDao storeRoleDao;
    @Resource
    private FeignOrderClient feignOrderClient;
    @Resource
    private FeignGoodsClient feignGoodsService;
    @Resource
    private YoshopStoreMenuDao storeMenuDao;
    @Resource
    private FeignMediaClient feignMediaClient;
    @Resource
    private YoshopUserService userService;
    @Resource
    private YoshopUserDao userDao;
    @Resource
    private YoshopRechargeOrderDao rechargeOrderDao;

    @Override
    public List<YoshopStoreRoleEntity> queryStoreRoleList(Integer storeId) {
        LambdaQueryWrapper<YoshopStoreRoleEntity> lqw =  new LambdaQueryWrapper<>();
        lqw.eq(YoshopStoreRoleEntity::getStoreId,storeId);
        lqw.orderByAsc(YoshopStoreRoleEntity::getSort);
        List<YoshopStoreRoleEntity> storeRoleEntities = storeRoleDao.selectList(lqw);
        storeRoleEntities.forEach(storeRoleEntity -> storeRoleEntity.setCreateTime(DateFormatUtils.formatDatetime(storeRoleEntity.getCreateTime())));
        return storeRoleEntities;
    }

    @Override
    public StoreDataDto storeData() {
        // 1、实时交易概况
        Map<String, Object> overview = feignOrderClient.queryOverview();
        // 新增会员数
        Map<String, Object> userByDay = userService.queryNewUserByday();
        overview.put("newUserTotal", userByDay);
        // 2、统计数据
        // 订单概况
        // 商品总数量
        long goodsTotal = feignGoodsService.queryTotalGoods();
        Map<String, Object> statistics = feignOrderClient.queryConsumption();
        List<Integer> userIds = userService.queryUserIds();
        statistics.put("goodsTotal", String.valueOf(goodsTotal));
        statistics.put("userTotal", String.valueOf(userIds.size()));
        // 3、待发货订单(笔)
        Map<String, Object> pending = feignOrderClient.queryPending();
        // 已售罄商品
        long soldOutGoodsTotal = feignGoodsService.querySoldOutGoodsTotal();
        pending.put("soldoutGoodsTotal", String.valueOf(soldOutGoodsTotal));


        // 4、获取近七日交易走势
        TradeTrendVO tradeTrend = feignOrderClient.getTradeTrend();

        StoreDataDto storeData = new StoreDataDto();
        storeData.setOverview(overview);
        storeData.setStatistics(statistics);
        storeData.setPending(pending);
        storeData.setTradeTrend(tradeTrend);

        return storeData;
    }

    @Override
    public List<YoshopStoreMenuEntity> queryStoreMenuList(Integer storeId) {
        List<YoshopStoreMenuEntity> menuEntities = storeMenuDao.selectList(null);
        // todo 用户管理
        // menuEntities.stream().filter(menuEntity -> menuEntity.getParentId() == 0)
        //         .map(menu -> {
        //             menu.setChildren(storeMenuDao.selectList(new LambdaQueryWrapper<YoshopStoreMenuEntity>()
        //                     .eq(YoshopStoreMenuEntity::getParentId, menu.getMenuId())));
        //             return menu;
        //         })
        //         .forEach(menu -> {
        //             menu.setCreateTime(DateFormatUtils.formatDatetime(menu.getCreateTime()));
        //             menu.setUpdateTime(DateFormatUtils.formatDatetime(menu.getUpdateTime()));
        //         })
        return null;
    }

    @Override
    public YoshopStoreEntity queryStoreInfo(Integer storeId) {
        YoshopStoreEntity storeEntity = this.getById(storeId);
        storeEntity.setCreateTime(DateFormatUtils.formatDatetime(storeEntity.getCreateTime()));
        storeEntity.setUpdateTime(DateFormatUtils.formatDatetime(storeEntity.getUpdateTime()));
        YoshopUploadFileEntity logoImage = feignMediaClient.queryFiles(storeEntity.getLogoImageId());
        storeEntity.setLogoImage(logoImage);
        storeEntity.setImage_url(logoImage.getPreviewUrl());
        return storeEntity;
    }

    @Override
    public boolean updateStoreInfo(EditStoreParamsDto param, Integer storeId) {
        EditStoreParamsDto.StoreForm form = param.getForm();
        YoshopStoreEntity store = this.getById(storeId);
        store.setLogoImageId(form.getLogoImageId());
        store.setDescribe(form.getDescribe());
        store.setStoreName(form.getStoreName());
        return this.updateById(store);
    }

    @Override
    public StoreSalesDto queryStatisticsData() {
        TradeTrendVO tradeTrend = feignOrderClient.getTradeTrend();
        List<Map<String, Object>> maps = feignOrderClient.queryOrderSales();
        List<StoreSalesDto.GoodsRanking> goodsRankingList = new ArrayList<>();
        maps.forEach(goods -> {
            StoreSalesDto.GoodsRanking goodsRanking = new StoreSalesDto.GoodsRanking();
            goodsRanking.setGoodsId(Integer.parseInt(goods.get("goods_id").toString()));
            goodsRanking.setGoodsName(goods.get("goods_name").toString());
            goodsRanking.setSalesVolume(goods.get("total_pay_price_sum").toString());
            goodsRanking.setTotalSalesNum(goods.get("total_sales").toString());
            goodsRankingList.add(goodsRanking);
        });


        StoreSalesDto.OverviewTrend overviewTrend = new StoreSalesDto.OverviewTrend();
        // 用户充值总额 (元)
        overviewTrend.setRechargeTotalMoney(rechargeOrderDao.rechargeMoney());
        // 支付订单数 (笔)
        Map<String, String> map = feignOrderClient.queryPayOrderCount();
        overviewTrend.setOrderTotal(map.get("pay_order_count"));
        // 销售额 (元)
        overviewTrend.setOrderTotalPrice(map.get("order_total_price"));
        // 会员数量
        overviewTrend.setUserTotal(String.valueOf(userDao.queryUserCount()));
        // 商品数量 (件)
        overviewTrend.setGoodsTotal(String.valueOf(feignGoodsService.queryTotalGoods()));
        // 消费人数
        overviewTrend.setConsumeUsers(map.get("user_count"));


        LambdaQueryWrapper<YoshopUserEntity> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(YoshopUserEntity::getExpendMoney);
        Page<YoshopUserEntity> userPage = userService.page(new Page<>(1, 5), lqw);
        List<YoshopUserEntity> userList =  userPage.getRecords();
        List<StoreSalesDto.UserExpendRanking> userExpendRanking = userList.stream().map(user -> {
            StoreSalesDto.UserExpendRanking userex = new StoreSalesDto.UserExpendRanking();
                    userex.setUserId(user.getUserId());
                    userex.setNickName(user.getNickName());
                    userex.setExpendMoney(user.getExpendMoney());
            return userex;
        }).collect(Collectors.toList());
        StoreSalesDto storeSales =  new StoreSalesDto();
        storeSales.setOverview(overviewTrend);
        storeSales.setTradeTrend(tradeTrend);
        storeSales.setGoodsRanking(goodsRankingList);
        storeSales.setUserExpendRanking(userExpendRanking);
        return storeSales;
    }


}